#!/bin/bash
BACKUP_BIN="/usr/local/mysql/bin/mysqlbinlog"
LOCAL_BACKDIR="/backup/binary/"
LOGDIR="/backup/binlog"
BACKUP_LOG="${LOGDIR}/backup.log"

HOST="47.52.96.106"
PORT="3306"
USER="repl"
PASS="As061129"
FIRST_BINLOG="mysql-bin.000001"
SLEEP_SECONDS=5
PROG=syncbin
PIDFILE="/backup/binlog/${PROG}.pid"
. /etc/init.d/functions

[ -x /etc/init.d/${PROG} ] || exit 5

#判断目录是否存在
[ ! -d ${LOCAL_BACKDIR} ] && mkdir -p ${LOCAL_BACKDIR}
[ ! -d ${LOGDIR} ] && mkdir -p ${LOGDIR}
[ ! -f ${BACKUP_LOG} ] && touch ${BACKUP_LOG}

if [ `ls -A "${LOCAL_BACKDIR}" |wc -l` -eq 0 ];then
     LAST_FILE=${FIRST_BINLOG}
  else
     LAST_FILE=`ls -l ${LOCAL_BACKDIR}|tail -n 1 |awk '{print $9}'`
fi
case $1 in
start)
  if [ -e $PIDFILE ];then
	echo "syncbin is already running ....."
	exit 3
  else
  	/usr/bin/nohup  ${BACKUP_BIN} --raw -R --stop-never --host=${HOST} --port=${PORT} --user=${USER} --password=${PASS} ${LAST_FILE} -r ${LOCAL_BACKDIR} &
	retval=$?
  fi
  if [ $retval -eq 0 ];then
	action "start sync binlog....." /bin/true
	touch $PIDFILE 
  else
	action "start sync binlog....." /bin/false 
  fi
  ;;
stop)
  PID=$(pidof mysqlbinlog) && kill -9 $PID 

  if [ -f $PIDFILE ];then
	 rm -rf $PIDFILE
  fi
  if [ $? -eq 0  ];then
	action "stop sync binlog" /bin/true
  else
	action "stop sync binlog" /bin/false
  fi
  ;;
esac
#可以通过监听这个进程，或者测试ping，然后连接mysql是否正常
